﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DevExpress.Wpf.Editors.Settings;
using Business.Compta;
using DAO.Compta;
using Manageo;

namespace Compta
{
    /// <summary>
    /// Interaction logic for AccountsUI.xaml
    /// </summary>
    public partial class AccountsUI : UserControl
    {
        private ObservableCollection<Account> _accounts;
        private ObservableCollection<SelectedUser> _selectedUsers;
        private ObservableRangeCollection<User> _owners = 
            new ObservableRangeCollection<User>();
        private ObservableRangeCollection<CategoriesPerUser> _categoriesPerUsers =
            new ObservableRangeCollection<CategoriesPerUser>();

        public ObservableCollection<Account> Accounts
        {
            get
            {
                if (_accounts == null)
                {
                    _accounts = new ObservableCollection<Account>(ComptaAccountsDAO.getAllAccounts());
                }
                return _accounts;
            }
        }
        
        public ObservableCollection<SelectedUser> SelectedUsers
        {
            get
            {
                if (_selectedUsers == null)
                {
                    _selectedUsers = new ObservableCollection<SelectedUser>();
                    List<User> allUsers = ComptaUsersDAO.getAllUsers();
                    foreach (User user in allUsers)
                    {
                        _selectedUsers.Add(new SelectedUser(true,user,false));
                    }
                }
                return _selectedUsers;
            }
        }
        
        public ObservableRangeCollection<User> Owners
        {
            get
            {
                if (_owners == null)
                {
                    _owners = new ObservableRangeCollection<User>();
                }
                return _owners;
            }
        }

        public ObservableRangeCollection<CategoriesPerUser> CategoriesPerUsers
        {
            get
            {
                if (_categoriesPerUsers == null)
                {
                    _categoriesPerUsers = new ObservableRangeCollection<CategoriesPerUser>();
                }
                return _categoriesPerUsers;
            }
        }

        private int idAccount=1;

        public AccountsUI()
        {
                InitializeComponent();
        }

        #region Modification on Account
        private void validateAccount(object sender, DevExpress.Wpf.Grid.GridRowValidationEventArgs e)
        {
            Account line = (Account)e.Row;
            if (line != null)
            {
                if (line.Id == -1)
                {
                    try
                    {
                        line.Id = ComptaAccountsDAO.InserNewAccount(line);
                        line.commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("error while modifying or insert account line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        _accounts.Remove(line);
                    }
                }
                else
                {
                    try
                    {
                        ComptaAccountsDAO.ModifyAccount(line);
                        line.commit();
                    }
                    catch (Exception ex)
                    {
                        line.reject();
                        MessageBox.Show("error while modifying or insert account line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

        }

        private void keyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DevExpress.Wpf.Grid.TableView view = (DevExpress.Wpf.Grid.TableView)sender;
                if (view.ActiveEditor == null || !view.ActiveEditor.IsEditorActive)
                {
                    int listIndex = this.gridControl1.GetRowListIndex(view.FocusedRowHandle);
                    ObservableCollection<Account> list =
                        (ObservableCollection<Account>)this.gridControl1.DataSource;
                    if (listIndex >= 0)
                    {
                        Account line = list[listIndex];
                        try
                        {
                            int _return = ComptaAccountsDAO.deleteAccount(line);
                            if (_return == 1)
                            {
                                list.RemoveAt(listIndex);
                            }
                            else
                            {
                                MessageBox.Show("Le Compte n'a pas été supprimé. Voir Mamour !", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("error while deleting Account line (id = " + line.Id + ")\n" + ex.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
        }
        #endregion

        #region Modification on Owners
        private void validateAccount(object sender, DevExpress.Wpf.Grid.FocusedRowChangedEventArgs e)
        {
                if (view.FocusedRowHandle >= 0 && _selectedUsers != null)
                {
                    int listIndex = this.gridControl1.GetRowListIndex(view.FocusedRowHandle);
                    ObservableCollection<Account> list =
                        (ObservableCollection<Account>)this.gridControl1.DataSource;
                    Account line = list[listIndex];
                    idAccount = line.Id;
                    this._owners.ReplaceRange(ComptaUsersDAO.getOwners(idAccount));
                    this._categoriesPerUsers.ReplaceRange(ComptaCategoriesDAO.getCategoriesPerUser(idAccount));

                    List<int> listUsers = ComptaAccountsDAO.getUsersForAccount(line.Id);

                    foreach (SelectedUser user in SelectedUsers)
                    {
                        if (listUsers.Contains(user.User.Id))
                        {
                            user.IsSelected = true;
                            user.IsNew = false;
                        }
                        else
                        {
                            user.IsSelected = false;
                            user.IsNew = true;
                        }
                    }

                    reInitOwners();
                }
        }

        private void reInitOwners()
        {
            var restul = from c in SelectedUsers
                         where c.IsSelected == true
                         select c.User;
            _owners.Clear();
            foreach (User usr in restul)
            {
                _owners.Add(usr);
            }
        }

        private void click(object sender, RoutedEventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            SelectedUser user = (SelectedUser)chk.DataContext;
            bool isChecked = (bool)chk.IsChecked;
            try
            {
                if (isChecked)
                {
                    ComptaAccountsDAO.insertUserForAccount(idAccount, user.User.Id);

                }
                else
                {
                    int _return = ComptaAccountsDAO.deleteUserForAccount(idAccount, user.User.Id);

                    if (_return != 1)
                    {
                        user.IsSelected = true;
                        MessageBox.Show("L'utilisateur n'a pas été enlevé du compte. Voir Mamour !", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                }

                reInitOwners();
            }
            catch (Exception ex)
            {
                MessageBox.Show("error while (un)selecting user (user = " + user.User.UserName + " ; account = " + idAccount + ")\n" + ex.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        public class SelectedUser : INotifyPropertyChanged
        {
            private bool isNew;
            public bool IsNew
            {
                get
                {
                    return this.isNew;
                }
                set
                {
                    this.isNew = value;
                }
            }
            private User user;
            public User User
            {
                get
                {
                    return this.user;
                }
                set
                {
                    this.user = value;
                }
            }
            private Boolean isSelected;
            public Boolean IsSelected
            {
                get
                {
                    return this.isSelected;
                }
                set
                {
                    this.isSelected = value;
                    onPropertyChanged("IsSelected");
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;
            event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
            {

                add
                {

                    PropertyChanged += value;

                }

                remove
                {

                    PropertyChanged -= value;

                }

            }
            protected void onPropertyChanged(string PropertyName)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }


            public SelectedUser(bool _isNew, User _user, Boolean _isSelected)
            {
                this.isNew = _isNew;
                this.user = _user;
                this.isSelected = _isSelected;
            }
        }

        private void CategoriesView_ValidateRow(object sender, DevExpress.Wpf.Grid.GridRowValidationEventArgs e)
        {
            CategoriesPerUser line = (CategoriesPerUser)e.Row;
            if (line != null)
            {
                if (line.Id == -1)
                {
                    try
                    {
                        line.IdAccount = idAccount;
                        line.Id = ComptaCategoriesDAO.InserNewCategoryPerUser(line);
                        line.commit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("error while modifying or insert categories line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        _categoriesPerUsers.Remove(line);
                    }
                }
                else
                {
                    try
                    {
                        ComptaCategoriesDAO.ModifyCategoryPerUser(line);
                        line.commit();
                    }
                    catch (Exception ex)
                    {
                        line.reject();
                        MessageBox.Show("error while modifying or insert categories line ! (id = " + line.Id + ")\n" + ex, "Error !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        private void CategoriesView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DevExpress.Wpf.Grid.TableView view = (DevExpress.Wpf.Grid.TableView)sender;
                if (view.ActiveEditor == null || !view.ActiveEditor.IsEditorActive)
                {
                    int listIndex = this.gridControl1.GetRowListIndex(view.FocusedRowHandle);
                    ObservableCollection<CategoriesPerUser> list =
                        (ObservableCollection<CategoriesPerUser>)this.categoriesPerUser.DataSource;
                    if (listIndex >= 0)
                    {
                        CategoriesPerUser line = list[listIndex];
                        try
                        {
                            int _return = ComptaCategoriesDAO.deleteCategoryPerUser(line);
                            if (_return == 1)
                            {
                                list.RemoveAt(listIndex);
                            }
                            else
                            {
                                MessageBox.Show("La ligne n'a pas été supprimée. Voir Mamour !", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("error while deleting line (id = " + line.Id + ")\n" + ex.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
        }

        private void categoriesPerUser_Loaded(object sender, RoutedEventArgs e)
        {
            this.categoriesPerUser.Columns["IdUser"].EditSettings = new ComboBoxEditSettings() { DisplayMember = "Login", ValueMember = "Id", IsTextEditable = true, ItemsSource = (this.Owners as ObservableRangeCollection<User>) };
        }



    }

    
}
